/**
 * created by zhoulli on 2018/7/10
 * 1.表格加载预览
 * 2.编辑表格的列字段，修改名称，是否显示
 */
import {messages} from "share/common";
import React from 'react';
import {connect} from 'react-redux';
import {Button, Table, Popconfirm, Modal, Switch, Icon} from 'antd';
import 'styles/basic-data/bank-definition/bank-definition.scss';
import "styles/data-center/report/travel-report/travel-report-setting.scss";
import TRService from 'containers/data-center/report/travel-report/travel-report.service';
import ReportFieldsEditor from "containers/data-center/report/travel-report/components/report-fields-editor";
import moment from "moment";
class TravelReportSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      reportDetail: {},
      //列名：根据后端定
      columns: [
        {
          title: messages('data-center.key9'/*公司*/),
          key: "companyName",
          dataIndex: 'companyName',
        },
      ],
      searchForm: [],
      //报表数据
      data: [],
      setReportField: false,
      //模态编辑框-列字段的数据
      dataColumnsModal: [],
    }
  }

  componentDidMount() {
    this.getReportDetail(this.props.params.id);
  }

  //获取表详细结构

  getReportDetail = (id) => {
    TRService.getReportDetail(id)
      .then((res) => {
        this.setState({
          reportDetail: res.data,
          columns: res.data.setColumnByMan,
          searchForm: res.data.searchFormByMan,
          dataColumnsModal: res.data.dataColumnsByMan,

        }, () => {
          this.getTravelDataList()
        })
      })
  };

  //获取报表数据
  getTravelDataList = () => {
    const reportId = this.props.params.id;
    this.setState({loading: true});
    //只查询前三个月
    let searchForm = this.state.searchForm;
    let params = {
      id: reportId,
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize,
    };
    let needRequest = _getNeedRequestParams(searchForm);
    params["criteria"] = _setParams(needRequest);
    TRService.getTravelDataList(params)
      .then((res) => {
        this.setState({
          data: res.data,
          loading: false
        })
      })
      .catch(() => {
        this.setState({
          loading: false
        })
      });
    /*
   * 把必须要上传的参数挑出来，
   * 目前就 date date_month
   * */
    function _getNeedRequestParams(searchForm) {
      let len = searchForm.length;
      let resObj = [];
      for (let i = 0; i < len; i++) {
        let item = searchForm[i];
        if (item.backend_id === "date" || item.backend_id === "date_month") {
          resObj.push(item)
        }
        if (item.backend_id === "expense_create_date" && item.id === 'receipt_date' && Number(reportId) === 15) { // 发票汇总报表开票日期
          resObj.push(item)
        }
      }
      return resObj;
    }

    /*
    * 处理需要上传的参数
    * */
    function _setParams(needRequest) {
      let len = needRequest.length;
      let resObj = {};

      /**
       * 这什么鬼东西啊
       * 一坨💩
       * 不想掺合这东西，另开一个循环了
       */
      for (let i = 0; i < len; i += 2) {
        let item = needRequest[i], itemNext = needRequest[i + 1];
        let startTime = "", endTime = "";
        if (item.backend_id === "date") {
          startTime = item.defaultValue.format("YYYY-MM-DD");
          endTime = itemNext.defaultValue.format("YYYY-MM-DD");
        }
        if (item.backend_id === "date_month") {
          startTime = item.defaultValue.format("YYYY-MM");
          endTime = itemNext.defaultValue.format("YYYY-MM");
        }
        let time = JSON.stringify([startTime, endTime]);
        let _defaultKey = (item.id).split("_$$_");
        let defaultKey = _defaultKey[0];
        resObj[defaultKey] = time;
      }

      needRequest.forEach(item => {
        if (item.backend_id === "expense_create_date" && item.id === 'receipt_date' && Number(reportId) === 15) { // 发票汇总报表开票日期
          resObj[item.id] = JSON.stringify(item.defaultValue.map(date => {
            let result = moment(date).format("YYYY-MM-DD");
            return result !== "Invalid date" ? result : null
          }));
        }
      })
      return resObj
    }

  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        total: pagination.total
      }
    }, () => {
      this.getTravelDataList();
    })
  };

  setReportFieldShow = () => {
    this.setState({
      setReportField: true
    })
  };

  //点击确定：修改列
  setReportFieldOk = (dataColumnsModal) => {
    this.setState({
      dataColumnsModal,
      loading: true,
      setReportField: false,
    }, () => {
      this.getReportDetail(this.props.params.id);
    });
  };

  //取消设置
  setReportFieldCancel = () => {
    this.setState({
      setReportField: false
    })
  };

  handleBack = () => {
    this.context.router.goBack();
  };

  render() {
    let {columns, data, loading, setReportField, dataColumnsModal} = this.state;
    const {setReportFieldCancel, setReportFieldOk} = this;
    return (
      <div className="travel-report-setting-wrap">
        <div className="title-wrap-name">
          {this.state.reportDetail.reportName}
        </div>
        <div className="table-header">
          <div className="table-header-title">
            <Button onClick={this.setReportFieldShow} type="primary">
              {messages('data-center.key15'/*字段编辑*/)}
            </Button>
          </div>
        </div>
        <Table
          scroll={{x: columns.length * 200}}
          dataSource={data}
          loading={loading}
          onChange={this.onChangePager}
          columns={columns}
          size="middle"
          bordered/>

        <ReportFieldsEditor
          visible={setReportField}
          onClose={setReportFieldCancel}
          fields={dataColumnsModal}
          onSave={setReportFieldOk}
          isSubmitting={loading}>
        </ReportFieldsEditor>

        <div>
          <a style={{fontSize: '14px', paddingBottom: '20px'}} onClick={this.handleBack}>
            <Icon type="rollback" style={{marginRight: '5px'}}/>
            {messages('common.back')}
          </a>
        </div>

      </div>
    )
  }
}

TravelReportSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(TravelReportSetting);
